<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>简单的算法分析 | 给点给点</title><meta name="keywords" content="算法"><meta name="author" content="夙星夜寐"><meta name="copyright" content="夙星夜寐"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="[TOC] 穷举法​        将问题的所有可能的答案一一列举（这就是穷举），然后根据条件判断此答案是否合适，合适就保留，不合适就丢弃 百鸡问题鸡翁一，值钱五，鸡母一，值钱三，鸡雏三，值钱一，百钱买百鸡，问翁、母、雏各几何？输入：无输出：鸡翁，鸡母，鸡雏的数量 #include&lt;iostream&gt;using namespace std;int main() &amp;#123;	for (">
<meta property="og:type" content="article">
<meta property="og:title" content="简单的算法分析">
<meta property="og:url" content="https://gitee.com/wawanaB_psgr/blog/2022/07/15/%E7%AE%80%E5%8D%95%E7%9A%84%E7%AE%97%E6%B3%95%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="给点给点">
<meta property="og:description" content="[TOC] 穷举法​        将问题的所有可能的答案一一列举（这就是穷举），然后根据条件判断此答案是否合适，合适就保留，不合适就丢弃 百鸡问题鸡翁一，值钱五，鸡母一，值钱三，鸡雏三，值钱一，百钱买百鸡，问翁、母、雏各几何？输入：无输出：鸡翁，鸡母，鸡雏的数量 #include&lt;iostream&gt;using namespace std;int main() &amp;#123;	for (">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/wawanaB_psgr/blog/img/default_cover.png">
<meta property="article:published_time" content="2022-07-15T04:57:27.000Z">
<meta property="article:modified_time" content="2022-07-29T06:21:27.520Z">
<meta property="article:author" content="夙星夜寐">
<meta property="article:tag" content="算法">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/wawanaB_psgr/blog/img/default_cover.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://gitee.com/wawanaB_psgr/blog/2022/07/15/%E7%AE%80%E5%8D%95%E7%9A%84%E7%AE%97%E6%B3%95%E5%88%86%E6%9E%90/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-center"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '简单的算法分析',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-29 14:21:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.1.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/blog/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">7</div></a></div><div class="data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">7</div></a></div><div class="data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/timeline/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/blog/myself"><i class="fa-fw /myself/"></i><span> 1</span></a></li><li><a class="site-page child" href="/blog/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 2</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/img/default_cover.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">给点给点</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/timeline/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/blog/myself"><i class="fa-fw /myself/"></i><span> 1</span></a></li><li><a class="site-page child" href="/blog/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 2</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">简单的算法分析</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-07-15T04:57:27.000Z" title="发表于 2022-07-15 12:57:27">2022-07-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-29T06:21:27.520Z" title="更新于 2022-07-29 14:21:27">2022-07-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E7%AE%97%E6%B3%95/">算法</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="简单的算法分析"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>[TOC]</p>
<h2><span id="穷举法">穷举法</span></h2><p>​        将问题的所有可能的答案一一列举（这就是穷举），然后根据条件判断此答案是否合适，合适就保留，不合适就丢弃</p>
<h3><span id="百鸡问题">百鸡问题</span></h3><p>鸡翁一，值钱五，鸡母一，值钱三，鸡雏三，值钱一，百钱买百鸡，问翁、母、雏各几何？<br>输入：无<br>输出：鸡翁，鸡母，鸡雏的数量</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; <span class="number">5</span> * i &lt;= <span class="number">100</span>; i++) &#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> j = <span class="number">0</span>; <span class="number">5</span> * i + <span class="number">3</span> * j &lt;= <span class="number">100</span>; j++) &#123;</span><br><span class="line">			<span class="keyword">for</span> (<span class="type">int</span> k = <span class="number">0</span>; <span class="number">5</span> * i + <span class="number">3</span> * j + k / <span class="number">3</span> &lt;= <span class="number">100</span>; k++) &#123;</span><br><span class="line">				<span class="keyword">if</span> (<span class="number">5</span> * i + <span class="number">3</span> * j + k / <span class="number">3</span> == <span class="number">100</span> &amp;&amp; i + j + k == <span class="number">100</span>)</span><br><span class="line">					cout &lt;&lt; i &lt;&lt; <span class="string">&quot; &quot;</span> &lt;&lt; j &lt;&lt; <span class="string">&quot; &quot;</span> &lt;&lt; k &lt;&lt; endl;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2><span id="递归与分治">递归与分治</span></h2><p>​        递归：若一个过程直接或间接地调用自己，则称这个过程是递归的过程。递归分为直接递归（自己调用自己）与间接递归（A调用B，B调用A）。<br>​        分治：所谓分治就是分而治之，对于一个较大规模的问题，使用分治的思想就是将它分为多个互相独立且与原问题形式相同的规模较小的问题，递归地解决这些子问题，然后将各子问题的解合并，即可得到原问题的解。</p>
<h3><span id="二分查找">二分查找</span></h3><p>假设本题给定数组为[1,3,4,6,8,9,13,16,20,25]，输入一个数x，使用二分查找的方法在给定数组中对其进行查找，若找到返回x的位置（索引），否则返回-1。<br>输入：需要查找的数x<br>输出：x的位置或者-1</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="type">int</span> a[] = &#123; <span class="number">1</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">13</span>, <span class="number">16</span>, <span class="number">20</span>, <span class="number">25</span> &#125;;</span><br><span class="line">	<span class="type">int</span> n;</span><br><span class="line">	cout &lt;&lt; <span class="string">&quot;查询什么数字&quot;</span>&lt;&lt;endl;</span><br><span class="line">	cin &gt;&gt; n;</span><br><span class="line"></span><br><span class="line">	<span class="type">int</span> left = <span class="number">0</span>, right = <span class="built_in">sizeof</span>(a) - <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span> (left&lt;=right) &#123;</span><br><span class="line">		<span class="keyword">if</span> (n == a[(left + right) / <span class="number">2</span>])</span><br><span class="line">		&#123;</span><br><span class="line">			cout &lt;&lt; (left + right) / <span class="number">2</span>+<span class="number">1</span>;</span><br><span class="line">			<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (n &gt; a[(left + right) / <span class="number">2</span>])</span><br><span class="line">			left = (left + right) / <span class="number">2</span> + <span class="number">1</span>;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">			right = (left + right) / <span class="number">2</span> - <span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	cout &lt;&lt; <span class="number">-1</span>;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3><span id="归并排序">归并排序</span></h3><p>给定默认数组[5,8,2,9,4,6,3,1,10,7]，使用合并排序的方法，将该数组按从小到大的顺序排序并输出。<br>输入：无<br>输出：1 2 3 4 5 6 7 8 9 10</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Copy</span><span class="params">(<span class="type">int</span> a[], <span class="type">int</span> b[], <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">//将b[0]至b[right-left+1]拷贝到a[left]至a[right]</span></span><br><span class="line">	<span class="type">int</span> size = right - left + <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; size; i++) &#123;</span><br><span class="line">		a[left++] = b[i];</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Merge</span><span class="params">(<span class="type">int</span> a[], <span class="type">int</span> b[], <span class="type">int</span> left, <span class="type">int</span> i, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">//合并有序数组a[left:i],a[i+1:right]到b,得到新的有序数组b</span></span><br><span class="line">	<span class="type">int</span> a1cout = left, <span class="comment">//指向第一个数组开头</span></span><br><span class="line">		a1end = i, <span class="comment">//指向第一个数组结尾</span></span><br><span class="line">		a2cout = i + <span class="number">1</span>, <span class="comment">//指向第二个数组开头</span></span><br><span class="line">		a2end = right, <span class="comment">//指向第二个数组结尾</span></span><br><span class="line">		bcout = <span class="number">0</span>; <span class="comment">//指向b中的元素</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="type">int</span> j = <span class="number">0</span>; j &lt; right - left + <span class="number">1</span>; j++) &#123;</span><br><span class="line">		<span class="comment">//执行right-left+1次循环，数组</span></span><br><span class="line">		<span class="keyword">if</span> (a1cout &gt; a1end) &#123;</span><br><span class="line">			b[bcout++] = a[a2cout++];</span><br><span class="line">			<span class="keyword">continue</span>;</span><br><span class="line">		&#125;  <span class="comment">//如果第一个数组结束，拷贝第二个数组的元素到b</span></span><br><span class="line">		<span class="keyword">if</span> (a2cout &gt; a2end) &#123;</span><br><span class="line">			b[bcout++] = a[a1cout++];</span><br><span class="line">			<span class="keyword">continue</span>;</span><br><span class="line">		&#125;  <span class="comment">//如果第二个数组结束，拷贝第一个数组的元素到b</span></span><br><span class="line">		<span class="keyword">if</span> (a[a1cout] &lt; a[a2cout]) &#123;</span><br><span class="line">			b[bcout++] = a[a1cout++];</span><br><span class="line">			<span class="keyword">continue</span>;</span><br><span class="line">		&#125;  <span class="comment">//如果两个数组都没结束，比较元素大小，把较小的放入b</span></span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			b[bcout++] = a[a2cout++];</span><br><span class="line">			<span class="keyword">continue</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">MergeSort</span><span class="params">(<span class="type">int</span> a[], <span class="type">int</span> left, <span class="type">int</span> right)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">//对数组a[left:right]进行合并排序</span></span><br><span class="line">	<span class="type">int</span>* b = <span class="keyword">new</span> <span class="type">int</span>[right - left + <span class="number">1</span>];</span><br><span class="line">	<span class="keyword">if</span> (left &lt; right) &#123;</span><br><span class="line">		<span class="type">int</span> i = (left + right) / <span class="number">2</span>;<span class="comment">//取中点</span></span><br><span class="line">		<span class="built_in">MergeSort</span>(a, left, i);<span class="comment">//左半边进行合并排序</span></span><br><span class="line">		<span class="built_in">MergeSort</span>(a, i + <span class="number">1</span>, right);<span class="comment">//右半边进行合并排序</span></span><br><span class="line">		<span class="built_in">Merge</span>(a, b, left, i, right);<span class="comment">//左右合并到b中</span></span><br><span class="line">		<span class="built_in">Copy</span>(a, b, left, right);<span class="comment">//从b拷贝回来</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span> n = <span class="number">10</span>;</span><br><span class="line">	<span class="type">int</span> a[] = &#123; <span class="number">5</span>,<span class="number">8</span>,<span class="number">2</span>,<span class="number">9</span>,<span class="number">4</span>,<span class="number">6</span>,<span class="number">3</span>,<span class="number">1</span>,<span class="number">10</span>,<span class="number">7</span> &#125;;</span><br><span class="line">	<span class="built_in">MergeSort</span>(a, <span class="number">0</span>, n - <span class="number">1</span>);</span><br><span class="line">	<span class="keyword">for</span> (<span class="type">int</span> j = <span class="number">0</span>; j &lt; n; j++) &#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot; &quot;</span> &lt;&lt; a[j];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="快速排序">快速排序</span></h3><p>给定默认数组[5,8,2,9,4,6,3,1,10,7]，使用快速排序的方法，将该数组按从小到大的顺序排序并输出。<br>输入：无<br>输出：1 2 3 4 5 6 7 8 9 10</p>
<p><img src= "" data-lazy-src="/blog/images/20220715_01.png" alt="20220715_01"></p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">Partition</span><span class="params">(<span class="type">int</span> a[],<span class="type">int</span> p,<span class="type">int</span> r)</span></span>&#123;</span><br><span class="line">    <span class="type">int</span> i=p,j=r+<span class="number">1</span>;</span><br><span class="line">    <span class="type">int</span> x=a[p];</span><br><span class="line">    <span class="comment">//将小于x的元素交换到左边区域，将大于x的元素交换到右边区域</span></span><br><span class="line">    <span class="keyword">while</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">        <span class="keyword">while</span>(a[++i]&lt;x&amp;&amp;i&lt;r); <span class="comment">//直到找到左边存在大于x的元素停止</span></span><br><span class="line">        <span class="keyword">while</span>(a[--j]&gt;x); <span class="comment">//直到找到右边存在小于x的元素停止</span></span><br><span class="line">        <span class="keyword">if</span>(i&gt;=j)&#123;</span><br><span class="line">            <span class="comment">//用来结束while循环</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//交换两个找到的元素的位置</span></span><br><span class="line">        <span class="built_in">swap</span>(a[i],a[j]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//此时已经找到了原来划分点x正确的位置，为a[j]</span></span><br><span class="line">    a[p]=a[j]; <span class="comment">//将以前雀占鸠巢的元素值放在a[p]上</span></span><br><span class="line">    a[j]=x; <span class="comment">//x回到正确的位置</span></span><br><span class="line">    <span class="keyword">return</span> j; <span class="comment">//从这里继续开始划分</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">QuickSort</span><span class="params">(<span class="type">int</span> a[],<span class="type">int</span> p,<span class="type">int</span> r)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(p&lt;r)&#123;</span><br><span class="line">        <span class="type">int</span> q=<span class="built_in">Partition</span>(a,p,r);</span><br><span class="line">        <span class="comment">//对左半段排序</span></span><br><span class="line">        <span class="built_in">QuickSort</span>(a,p,q<span class="number">-1</span>);</span><br><span class="line">        <span class="comment">//对右半段排序</span></span><br><span class="line">        <span class="built_in">QuickSort</span>(a,q+<span class="number">1</span>,r);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> a[]=&#123;<span class="number">5</span>,<span class="number">8</span>,<span class="number">2</span>,<span class="number">9</span>,<span class="number">4</span>,<span class="number">6</span>,<span class="number">3</span>,<span class="number">1</span>,<span class="number">10</span>,<span class="number">7</span>&#125;;</span><br><span class="line">    <span class="type">int</span> n=<span class="number">10</span>;</span><br><span class="line">    <span class="built_in">QuickSort</span>(a,<span class="number">0</span>,n<span class="number">-1</span>);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">0</span>;i&lt;n;i++)&#123;</span><br><span class="line">        cout&lt;&lt;a[i]&lt;&lt;<span class="string">&quot; &quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="循环赛日程表">循环赛日程表</span></h3><p>设有n&#x3D;2^k个运动员要进行网球循环赛。现要设计一个满足以下要求的比赛日程表：<br>每个选手必须与其他n-1个选手各赛一次；<br>每个选手一天只能赛一次；<br>循环赛一共进行n-1天。<br>按上述要求将比赛日程表设计成有n行和n-1列的表。在表中第i行和第j列处填入第i个选手在第j天遇到的选手。（无输入；输出一个日程表，二维数组表示）<br><img src= "" data-lazy-src="/blog/images/20220715_02.png" alt="20220715_02"></p>
<p><strong>算法思路：</strong>按分治策略，我们可以将所有的选手分为两半，则n个选手的比赛日程表可以通过n&#x2F;2个选手的比赛日程表来决定。递归地用这种一分为二的策略对选手进行划分，直到只剩下两个选手时，比赛日程表的制定就变得很简单。这时只要让这两个选手进行比赛就可以了</p>
<p><em><strong>算法步骤</strong>：</em></p>
<p>(1)用一个for循环输出日程表的第一行，for(int i&#x3D;1;i&lt;&#x3D;N;i++) a[1][i] &#x3D; i</p>
<p><img src= "" data-lazy-src="/blog/images/20220715_03.png" alt="20220715_03"></p>
<p> (2)然后定义一个m值，m初始化为1，m用来控制每一次填充表格时i（i表示行）和j（j表示列）的起始填充位置。</p>
<p> (3)用一个for循环将问题分成几部分，对于k&#x3D;3，n&#x3D;8，将问题分成3大部分，第一部分为，根据已经填充的第一行，填写第二行，第二部分为，根据已经填充好的第一部分，填写第三四行，第三部分为，根据已经填充好的前四行，填写最后四行。for (int s&#x3D;1;s&lt;&#x3D;k;s++)  N&#x2F;&#x3D;2; </p>
<p> (4)用一个for循环对③中提到的每一部分进行划分for(int t&#x3D;1;t&lt;&#x3D;N;t++)对于第一部分，将其划分为四个小的单元，即对第二行进行如下划分</p>
<p><img src= "" data-lazy-src="/blog/images/20220715_04.png" alt="20220715_04"></p>
<p> 同理，对第二部分（即三四行），划分为两部分，第三部分同理。</p>
<p>   (5) 最后，根据以上for循环对整体的划分和分治法的思想，进行每一个单元格的填充。填充原则是：对角线填充</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i=m+<span class="number">1</span>;i&lt;=<span class="number">2</span>*m;i++) <span class="comment">//i控制行      </span></span><br><span class="line"></span><br><span class="line">     <span class="keyword">for</span>(<span class="type">int</span> j=m+<span class="number">1</span>;j&lt;=<span class="number">2</span>*m;j++)  <span class="comment">//j控制列       </span></span><br><span class="line"></span><br><span class="line">     &#123; </span><br><span class="line"></span><br><span class="line">         a[i][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>]= a[i-m][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>-m];<span class="comment">/*右下角的值等于左上角的值 */</span> </span><br><span class="line"></span><br><span class="line">         a[i][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>-m] =a[i-m][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>];<span class="comment">/*左下角的值等于右上角的值 */</span></span><br><span class="line"></span><br><span class="line">    &#125; </span><br></pre></td></tr></table></figure>
<p>  <strong>运行过程</strong>：</p>
<p><img src= "" data-lazy-src="/blog/images/20220715_05.png" alt="20220715_05"></p>
<p><img src= "" data-lazy-src="/blog/images/20220715_06.png" alt="20220715_06"></p>
<p><img src= "" data-lazy-src="/blog/images/20220715_07.png" alt="20220715_07"></p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Table</span><span class="params">(<span class="type">int</span> k,<span class="type">int</span> **a)</span></span>&#123;</span><br><span class="line">    <span class="type">int</span> n=<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">1</span>;i&lt;=k;i++)&#123;</span><br><span class="line">        n*=<span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">1</span>;i&lt;=n;i++)&#123;</span><br><span class="line">        a[<span class="number">1</span>][i]=i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> m=<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> s=<span class="number">1</span>;s&lt;=k;s++)&#123;</span><br><span class="line">        n/=<span class="number">2</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> t=<span class="number">1</span>;t&lt;=n;t++)&#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">for</span>(<span class="type">int</span> i=m+<span class="number">1</span>;i&lt;=<span class="number">2</span>*m;i++)&#123;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">for</span>(<span class="type">int</span> j=m+<span class="number">1</span>;j&lt;=<span class="number">2</span>*m;j++)&#123;</span><br><span class="line">                    a[i][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>]=a[i-m][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>-m];</span><br><span class="line">                    a[i][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>-m]=a[i-m][j+(t<span class="number">-1</span>)*m*<span class="number">2</span>];</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        m*=<span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">//假设选手人数为8人</span></span><br><span class="line">    <span class="type">int</span> n=<span class="number">9</span>;</span><br><span class="line">    <span class="type">int</span> k=<span class="number">3</span>;</span><br><span class="line">    <span class="comment">//创建一个n行n列的数组，但只用到了[1:n-1][1:n-1]</span></span><br><span class="line">    <span class="type">int</span> **a=<span class="keyword">new</span> <span class="type">int</span>*[n];</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">0</span>;i&lt;n;i++)&#123;</span><br><span class="line">        a[i]=<span class="keyword">new</span> <span class="type">int</span>[n];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">Table</span>(k,a);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">1</span>;i&lt;n;i++)&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j=<span class="number">1</span>;j&lt;n;j++)&#123;</span><br><span class="line">            cout&lt;&lt;a[i][j]&lt;&lt;<span class="string">&quot; &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        cout&lt;&lt;endl;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2><span id="动态规划">动态规划</span></h2><p>动态规划是用来解决多阶段决策过程最优化的一种数量方法。其特点在于，它可以把一个n维决策问题变换为几个一维最优化问题，从而一个一个地去解决。必须对具体问题进行具体分析，运用动态规划的原理和方法，建立相应的模型，然后再用动态规划方法去求解。</p>
<p>动态规划算法适用于解<strong>最优化问题</strong>，通常可以按以下4个步骤设计（1~3为动态规划算法的基本骤）：</p>
<ol>
<li>找出最优解的性质，并刻画其特征结构</li>
<li>递归地定义最优值</li>
<li>以自底向上的方式计算最优值</li>
<li>根据计算最优值时得到的信息，构造最优解</li>
</ol>
<h3><span id="最长公共子序列">最长公共子序列</span></h3><p>给定两个序列X&#x3D;{A,B,C,B,D,A,B},Y&#x3D;{B,D,C,A,B,A}，找出X与Y的最长公共子序列。</p>
<p><strong>分析：</strong><br>按照解决动态规划问题的3个基本步骤的思路分步骤分析：</p>
<ol>
<li><p>第一：最长公共子序列的结构（找出最优解的性质，并刻画其特征结构）<br>设序列X&#x3D;{x1,x2,…,xm}和Y&#x3D;{y1,y2,…,yn}的最长公共子序列为Z&#x3D;{z1,z2,…,zk}，则有如下情况：<br>（由既然是公共子序列，那么Z中元素zi必然同时属于X和Y，下面X(m-1)&#x3D;{x1,x2,…,xm-1}，Y，Z同理）<br>若xm&#x3D;yn，则zk&#x3D;xm&#x3D;yn，且Z(k-1)是X(m-1)和Y(n-1)的最长公共子序列<br>若xm!&#x3D;yn且zk!&#x3D;xm，则Z是X(m-1)和Y的最长公共子序列<br>若xm!&#x3D;yn且zk!&#x3D;yn，则Z是X和Y(n-1)的最长公共子序列</p>
</li>
<li><p>第二：子问题的递归结构（递归地定义最优值）<br>由最长公共子序列问题的最优子结构性质可知，要找出X与Y的最长公共子序列，可按以下方式递归地进行：<br>当xm&#x3D;yn时，找出X(m-1)和Y(n-1)的最长公共子序列，然后在其尾部加上xm（或yn），即可得X和Y的最长公共子序列。<br>当xm!&#x3D;yn时，必须解两个子问题，即找出X(m-1)和Y的一个最长公共子序列及X和Y(n-1)的一个最长公共子序列。这两个子问题都包含一个公共子问题，即计算X(m-1)和Y(n-1)的最长公共子序列。</p>
</li>
<li><p>第三：计算最优值（以自底向上的方式计算最优值）<br>首先建立子问题最优值的递归关系。用c[i][j]来记录序列Xi和Yj的最长公共子序列的长度。其中，Xi&#x3D;{x1,x2,…,xi}；Y同理。当i&#x3D;0或j&#x3D;0时，空序列是Xi和Yj的最长公共子序列，此时c[i][j]&#x3D;0。其他情况下，由最优子结构性质可建立递归关系如下：</p>
<p><img src= "" data-lazy-src="/blog/images/20220715_08.png" alt="20220715_08"></p>
<p>最后使用用动态规划自底向上计算最优值。</p>
</li>
</ol>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="type">char</span> a[<span class="number">500</span>],b[<span class="number">500</span>];</span><br><span class="line"><span class="type">char</span> num[<span class="number">501</span>][<span class="number">501</span>]; <span class="comment">///记录中间结果的数组</span></span><br><span class="line"><span class="type">char</span> flag[<span class="number">501</span>][<span class="number">501</span>];    <span class="comment">///标记数组，用于标识下标的走向，构造出公共子序列</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">LCS</span><span class="params">()</span></span>; <span class="comment">///动态规划求解</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">getLCS</span><span class="params">()</span></span>;    <span class="comment">///采用倒推方式求最长公共子序列</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> i;</span><br><span class="line">    <span class="built_in">strcpy</span>(a,<span class="string">&quot;ABCBDAB&quot;</span>);</span><br><span class="line">    <span class="built_in">strcpy</span>(b,<span class="string">&quot;BDCABA&quot;</span>);</span><br><span class="line">    <span class="built_in">memset</span>(num,<span class="number">0</span>,<span class="built_in">sizeof</span>(num));</span><br><span class="line">    <span class="built_in">memset</span>(flag,<span class="number">0</span>,<span class="built_in">sizeof</span>(flag));</span><br><span class="line">    <span class="built_in">LCS</span>();</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>,num[<span class="built_in">strlen</span>(a)][<span class="built_in">strlen</span>(b)]);</span><br><span class="line">    <span class="built_in">getLCS</span>();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">LCS</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> i,j;</span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">1</span>;i&lt;=<span class="built_in">strlen</span>(a);i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">for</span>(j=<span class="number">1</span>;j&lt;=<span class="built_in">strlen</span>(b);j++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span>(a[i<span class="number">-1</span>]==b[j<span class="number">-1</span>])   <span class="comment">///注意这里的下标是i-1与j-1</span></span><br><span class="line">            &#123;</span><br><span class="line">                num[i][j]=num[i<span class="number">-1</span>][j<span class="number">-1</span>]+<span class="number">1</span>;</span><br><span class="line">                flag[i][j]=<span class="number">1</span>;  <span class="comment">///斜向下标记</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span>(num[i][j<span class="number">-1</span>]&gt;num[i<span class="number">-1</span>][j])</span><br><span class="line">            &#123;</span><br><span class="line">                num[i][j]=num[i][j<span class="number">-1</span>];</span><br><span class="line">                flag[i][j]=<span class="number">2</span>;  <span class="comment">///向右标记</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">            &#123;</span><br><span class="line">                num[i][j]=num[i<span class="number">-1</span>][j];</span><br><span class="line">                flag[i][j]=<span class="number">3</span>;  <span class="comment">///向下标记</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">getLCS</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">char</span> res[<span class="number">500</span>];</span><br><span class="line">    <span class="type">int</span> i=<span class="built_in">strlen</span>(a);</span><br><span class="line">    <span class="type">int</span> j=<span class="built_in">strlen</span>(b);</span><br><span class="line">    <span class="type">int</span> k=<span class="number">0</span>;    <span class="comment">///用于保存结果的数组标志位</span></span><br><span class="line">    <span class="keyword">while</span>(i&gt;<span class="number">0</span> &amp;&amp; j&gt;<span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span>(flag[i][j]==<span class="number">1</span>)   <span class="comment">///如果是斜向下标记</span></span><br><span class="line">        &#123;</span><br><span class="line">            res[k]=a[i<span class="number">-1</span>];</span><br><span class="line">            k++;</span><br><span class="line">            i--;</span><br><span class="line">            j--;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span>(flag[i][j]==<span class="number">2</span>)  <span class="comment">///如果是斜向右标记</span></span><br><span class="line">            j--;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span>(flag[i][j]==<span class="number">3</span>)  <span class="comment">///如果是斜向下标记</span></span><br><span class="line">            i--;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(i=k<span class="number">-1</span>;i&gt;=<span class="number">0</span>;i--)</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%c&quot;</span>,res[i]);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="0-1背包问题">0-1背包问题</span></h3><p>给定n种物品和一背包。物品i的重量是wi，其价值为vi，背包的容量为c。问应如何选择装入背包中的物品，使得装入背包中的物品的总价值最大？<br><strong>分析：</strong><br>0-1背包问题中，对每种物品只有装入或不装入两种选择，并且不能将物品i装入背包多次，也不能只装入部分的物品i。首先将此问题形式化描述：要求找出一个n元0-1向量(x1,x2,…,xn)，x&#x3D;0或x&#x3D;1，使得w1x1+w2x2+…+wnxn&lt;&#x3D;c，而且v1x1+v2x2+…vnxn达到最大。</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">FindMax</span><span class="params">()</span><span class="comment">//动态规划</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> i,j;</span><br><span class="line">    <span class="comment">//填表</span></span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">1</span>;i&lt;=number;i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">for</span>(j=<span class="number">1</span>;j&lt;=capacity;j++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span>(j&lt;w[i])<span class="comment">//包装不进</span></span><br><span class="line">            &#123;</span><br><span class="line">                V[i][j]=V[i<span class="number">-1</span>][j];</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span><span class="comment">//能装</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">if</span>(V[i<span class="number">-1</span>][j]&gt;V[i<span class="number">-1</span>][j-w[i]]+v[i])<span class="comment">//不装价值大</span></span><br><span class="line">                &#123;</span><br><span class="line">                    V[i][j]=V[i<span class="number">-1</span>][j];</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span><span class="comment">//前i-1个物品的最优解与第i个物品的价值之和更大</span></span><br><span class="line">                &#123;</span><br><span class="line">                    V[i][j]=V[i<span class="number">-1</span>][j-w[i]]+v[i];</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2><span id="贪心算法">贪心算法</span></h2><p><strong>基本思想</strong><br>贪心算法并不从整体最优上加以考虑，所做的选择只是在某种意义上的局部最优选择。贪心算法中，较大子问题的解恰好包含了较小子问题的解作为子集。<br>贪心算法的一般框架：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="built_in">GreedyAlgorithm</span>(parameters)&#123;</span><br><span class="line">	初始化;</span><br><span class="line">	重复执行以下操作:</span><br><span class="line">		选择当前可以选择的最优解;</span><br><span class="line">		将所选择的当前解加入到问题的解中;</span><br><span class="line">	直至满足问题求解的结束条件。</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="活动安排问题">活动安排问题</span></h3><p>有n个活动申请使用同一个礼堂，每项活动有一个开始时间和一个截止时间，如果任何两个活动不能同时举行，问如何选择这些活动，从而使得被安排的活动数达到最多？<br><strong>分析：</strong><br>本题可形式化为：设S&#x3D;{1,2,…,n}为活动集合，si和fi分别为活动的开始和截止时间，i&#x3D;1,2,…,n。定义活动i与j相容：si&gt;&#x3D;fj或者sj&gt;&#x3D;fi，i!&#x3D;j，求S最大的两两相容的活动子集。</p>
<table>
<thead>
<tr>
<th>i</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>10</th>
<th>11</th>
</tr>
</thead>
<tbody><tr>
<td>s[i]</td>
<td>1</td>
<td>3</td>
<td>0</td>
<td>5</td>
<td>3</td>
<td>5</td>
<td>6</td>
<td>8</td>
<td>8</td>
<td>2</td>
<td>12</td>
</tr>
<tr>
<td>f[i]</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
</tbody></table>
<p><strong>使用策略：早完成的活动先安排</strong><br>把活动按照截止时间从小到大排序，使得f1&lt;&#x3D;f2&lt;&#x3D;…&lt;&#x3D;fn，然后从前向后挑选，只要与前面选择的活动相容，便将这项活动选入最大相容集合A。该算法的贪心选择的意义是：使剩余的可安排时间段极大化，以便安排尽可能多的相容活动。</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="comment">//注意活动的排序是按照结束时间非递减排序</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">GreedySelector</span><span class="params">(<span class="type">int</span> n,<span class="type">int</span> s[],<span class="type">int</span> f[],<span class="type">bool</span> A[])</span></span>&#123;</span><br><span class="line">    <span class="comment">//进行活动选择，将是否选择活动的情况存入bool数组A中</span></span><br><span class="line">    <span class="comment">//从第一个活动开始（第一个活动必选）</span></span><br><span class="line">    A[<span class="number">0</span>]=<span class="literal">true</span>;</span><br><span class="line">    <span class="type">int</span> j=<span class="number">0</span>; <span class="comment">//当前活动索引</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">1</span>;i&lt;n;i++)&#123; <span class="comment">//遍历从第2个活动开始的所有活动，i是下一个等待判断的活动索引</span></span><br><span class="line">        <span class="keyword">if</span>(s[i]&gt;=f[j])&#123;</span><br><span class="line">            <span class="comment">//如果索引为i的活动起始时间大于当前活动的结束时间（当前活动已结束）</span></span><br><span class="line">            A[i]=<span class="literal">true</span>; <span class="comment">//选定索引为i的活动</span></span><br><span class="line">            j=i; <span class="comment">//将当前活动置为索引为i的活动</span></span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="comment">//如果索引为i的活动起始时间小于当前活动的结束时间（当前活动未结束）</span></span><br><span class="line">            A[i]=<span class="literal">false</span>;  <span class="comment">//不选定</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> n=<span class="number">11</span>;</span><br><span class="line">    <span class="type">int</span> s[n]=&#123;<span class="number">1</span>,<span class="number">3</span>,<span class="number">0</span>,<span class="number">5</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">8</span>,<span class="number">8</span>,<span class="number">2</span>,<span class="number">12</span>&#125;;</span><br><span class="line">    <span class="type">int</span> f[n]=&#123;<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>,<span class="number">11</span>,<span class="number">12</span>,<span class="number">13</span>,<span class="number">14</span>&#125;;</span><br><span class="line">    <span class="type">bool</span> A[n]=&#123;<span class="literal">false</span>&#125;;</span><br><span class="line">    <span class="built_in">GreedySelector</span>(n,s,f,A);</span><br><span class="line">    cout&lt;&lt;<span class="string">&quot;选定了活动：&quot;</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">0</span>;i&lt;n;i++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(A[i])&#123;</span><br><span class="line">            cout&lt;&lt;i+<span class="number">1</span>&lt;&lt;<span class="string">&quot; &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="哈夫曼编码">哈夫曼编码</span></h3><p>频率高的字母对应短的编码，频率低的字母对应长的编码，相同信息转换为二进制后，传输的数据总量就会最低，要求找到一个编码方案，使传输的数据量最少。</p>
<p><strong>算法思路：</strong></p>
<p>以n个字母为结点构成n棵仅含一个点的二叉树集合，字母的频率即为结点的权。每次从二叉树集合中找出两个权最小者合并为一棵二叉树：增加一个根结点将这两棵树作为左右子树，新树的权为两棵子树的权之和。重复进行上述合并操作，直到只剩一棵树（即为哈夫曼树）为止。</p>
<p><img src= "" data-lazy-src="/blog/images/20220715_09.png" alt="20220715_09"></p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">class</span> <span class="title class_">T</span>&gt;</span><br><span class="line">BinaryTree&lt;<span class="type">int</span>&gt;<span class="built_in">HuffmanTree</span>(T f[],<span class="type">int</span> n)&#123;</span><br><span class="line">	<span class="comment">//根据权f[1:n]构造哈夫曼树</span></span><br><span class="line">	<span class="comment">//创建一个单结点数的数组</span></span><br><span class="line">	Huffman&lt;T&gt;*W=<span class="keyword">new</span> Huffman&lt;T&gt;[n+<span class="number">1</span>];</span><br><span class="line">	BinaryTree&lt;<span class="type">int</span>&gt; z,zero;</span><br><span class="line">	<span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">1</span>;i&lt;=n;i++)&#123;</span><br><span class="line">		z.<span class="built_in">MakeTree</span>(i,zero,zero);</span><br><span class="line">		W[i].weight=f[i];</span><br><span class="line">		W[i].tree=z;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//数组变成一个最小堆</span></span><br><span class="line">	MinHeap&lt;Huffman&lt;T&gt;&gt;<span class="built_in">Q</span>(<span class="number">1</span>);</span><br><span class="line">	Q.<span class="built_in">Initialize</span>(w,n,n);</span><br><span class="line">	<span class="comment">//将堆中的树不断合并</span></span><br><span class="line">	Huffman&lt;T&gt;x,<span class="function">y</span></span><br><span class="line"><span class="function">	<span class="title">for</span><span class="params">(i=<span class="number">1</span>;i&lt;n;i++)</span></span>&#123;</span><br><span class="line">		Q.<span class="built_in">DeleteMin</span>(x);</span><br><span class="line">		Q.<span class="built_in">DeleteMin</span>(y);</span><br><span class="line">		z.<span class="built_in">MakeTree</span>(<span class="number">0</span>,x.tree,y.tree);</span><br><span class="line">		<span class="comment">//合并权</span></span><br><span class="line">		x.weight+=y.weight;</span><br><span class="line">		x.tree=z;</span><br><span class="line">		Q.<span class="built_in">Insert</span>(x);</span><br><span class="line">	&#125;</span><br><span class="line">	Q.<span class="built_in">DeleteMin</span>(x); <span class="comment">//最后的树</span></span><br><span class="line">	Q.<span class="built_in">Deactivate</span>();</span><br><span class="line">	<span class="keyword">delete</span>[] w;</span><br><span class="line">	<span class="keyword">return</span> x.tree;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="单源最短路径">单源最短路径</span></h3><ul>
<li>给定一个图G&#x3D;（V,E），其中每条边的权是一个非负实数。另外给定V中的一个顶点v，称为源。求从源v到所有其它各个顶点的最短路径。</li>
</ul>
<p><img src= "" data-lazy-src="/blog/images/20220715_10.png" alt="20220715_10"></p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line">Procedure Dijkstra&#123;</span><br><span class="line">	S:=&#123;<span class="number">1</span>&#125;; <span class="comment">//初始化S</span></span><br><span class="line">	<span class="keyword">for</span> i:=<span class="number">2</span> to n <span class="keyword">do</span> <span class="comment">//初始化dis[]</span></span><br><span class="line">		dis[i]=C[<span class="number">1</span>,i] <span class="comment">//初始时为源到顶点i一步的距离</span></span><br><span class="line">	<span class="keyword">for</span> i:=<span class="number">1</span> to n <span class="keyword">do</span>&#123;</span><br><span class="line">		从V-S中选取一个顶点u使得dis[u]最小;</span><br><span class="line">		将u加入到S中; <span class="comment">//将新的最近者加入S</span></span><br><span class="line">		<span class="keyword">for</span> w ∈V-S <span class="keyword">do</span>&#123; <span class="comment">//依据最近者u修订dis[w]</span></span><br><span class="line">			<span class="comment">//这句话是Dijkstra的关键！！！选取最小距离并更新dis[]</span></span><br><span class="line">			dis[w]:=<span class="built_in">min</span>(dis[w],dis[u]+C[u,w]);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="最小生成树">最小生成树</span></h3><p>设G&#x3D;（V,E）是一个无向连通带权图，即一个网络。E的每条边（v,w）的权为c[v][w]。<br>如果G的一个子图G·是一颗包含G的所有顶点的树，则称G·为G的生成树。<br>生成树的各边的权的总和称为该生成树的耗费。<br>在G的所有生成树中，耗费最小的生成树称为G的最小（优）生成树。</p>
<p><strong>分析：</strong><br>本题我们使用Kruskal算法的思想来解决：在保证无回路的前提下依次选出权重较小的n-1条边。贪心策略：如果（i,j）是E中尚未被选中的边中权重最小的，并且（i,j）不会与已经选择的边构成回路，于是就选择（i,j）<br>定义如下数据结构：<br>结构数组e[]表示图的边，e[i].u、e[i].v、e[i].w分别表示边i的两个端点及其权重。<br>函数Sort(e,w)将数组e按权重w从小到大排序。<br>一个连通分支中的顶点表示为一个集合。<br>函数Initialize(n)将每个顶点初始化为一个集合。<br>函数Find(u)给出顶点u所在的集合。<br>函数Union(a,b)给出集合a和集合b的并集。<br>重载运算符!&#x3D;判断集合的不相等。</p>
<p><img src= "" data-lazy-src="/blog/images/20220715_11.png" alt="20220715_11"></p>
<p><img src= "" data-lazy-src="/blog/images/20220715_12.png" alt="20220715_12"></p>
<p><img src= "" data-lazy-src="/blog/images/20220715_13.png" alt="20220715_13"></p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="built_in">Kruskal</span>(<span class="type">int</span> n,*e)&#123;</span><br><span class="line">	<span class="built_in">Sort</span>(e,w); <span class="comment">//将边按权重从小到大排序</span></span><br><span class="line">	<span class="built_in">Initialze</span>(n); <span class="comment">//初始时每个顶点为一个集合</span></span><br><span class="line">	k=<span class="number">1</span>; <span class="comment">//k累计已选边的数目</span></span><br><span class="line">	j=<span class="number">1</span>; <span class="comment">//j为所选的边在e中的序号</span></span><br><span class="line">	<span class="keyword">while</span>(k&lt;n)&#123; <span class="comment">//选择n-1条边</span></span><br><span class="line">		a=<span class="built_in">Find</span>(e[j].u);b=<span class="built_in">Find</span>(e[j].v); <span class="comment">//找出第j条边的两个端点所在的集合</span></span><br><span class="line">		<span class="keyword">if</span>(a!=b)&#123;</span><br><span class="line">			<span class="comment">//若不同，第j条边放入树中并合并这两个集合</span></span><br><span class="line">			T[k]=j;</span><br><span class="line">			<span class="built_in">Union</span>(a,b);</span><br><span class="line">			k=k+<span class="number">1</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		j++; <span class="comment">//继续考察下一条边（仍按权重从小到大遍历）</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3><span id="背包问题">背包问题</span></h3><p>给定n个物品和一个背包，物品i的重量为wi，价值为vi，背包容量为C。如果在装入背包时，物品可以切割，即可以只装入一部分，问如何选择装入背包的物品的价值最大？（注意区分本题和动态规划中0-1背包问题的区别，0-1背包问题不适用于贪心算法）<br>设n&#x3D;3，C&#x3D;20，(v1,v2,v3)&#x3D;(25,24,15)，(w1,w2,w3)&#x3D;(18,15,10)<br><strong>分析：</strong><br>影响背包效益值的因素：背包的容量C、放入背包中的物品的重量及其可能带来的效益值<br>可行的策略：在背包效益值的增长速率和背包容量消耗速率之间取得平衡，即每次装入的物品应使它所占用的每一单位容量能获得当前最大的单位效益。<br>在这种策略下的量度是：已装入的物品的累计效益值与所用容量之比（单位重量价值）。<br>此时，将按照物品的单位效益值——vi&#x2F;wi值的非增次序进行选择：v1&#x2F;w1 &lt; v3&#x2F;w3 &lt; v2&#x2F;w2<br>即首先将物品2装入背包，其次选择装入物品3</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Knapsack</span><span class="params">(<span class="type">int</span> n,<span class="type">float</span> C,<span class="type">float</span> v[],<span class="type">float</span> w[],<span class="type">float</span> x[])</span></span>&#123;</span><br><span class="line">    <span class="comment">//Sort(n,v,w); //因为我们初始化的时候已经排好序，这里省略</span></span><br><span class="line">    <span class="type">int</span> i;</span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">1</span>;i&lt;=n;i++)&#123;</span><br><span class="line">        <span class="comment">//每种物品选取比例，初始化为0</span></span><br><span class="line">        x[i]=<span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">1</span>;i&lt;=n;i++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(w[i]&gt;C)&#123;</span><br><span class="line">            <span class="comment">//当前单位重量价值最大的物品，物品重量大于背包容量</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//当前单位重量价值最大的物品，物品重量不大于容量C，全部装入</span></span><br><span class="line">        x[i]=<span class="number">1</span>;</span><br><span class="line">        C-=w[i]; <span class="comment">//剩余容量减小w[i]</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(i&lt;=n)&#123;</span><br><span class="line">        <span class="comment">//说明触发了上面for循环中的break，直接用物品i填满剩下容量C即可</span></span><br><span class="line">        x[i]=C/w[i];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> n=<span class="number">3</span>; <span class="comment">//3件物品</span></span><br><span class="line">    <span class="type">float</span> C=<span class="number">20</span>; <span class="comment">//容量20</span></span><br><span class="line">    <span class="comment">//初始化，物品需要按单位重量价值非递减排序x1&gt;x2&gt;x3</span></span><br><span class="line">    <span class="type">float</span> v[<span class="number">4</span>]=&#123;<span class="number">0</span>,<span class="number">24</span>,<span class="number">15</span>,<span class="number">25</span>&#125;; <span class="comment">//因为是从索引1开始，所以v[0]用0填充</span></span><br><span class="line">    <span class="type">float</span> w[<span class="number">4</span>]=&#123;<span class="number">0</span>,<span class="number">15</span>,<span class="number">10</span>,<span class="number">18</span>&#125;; <span class="comment">//重量同理</span></span><br><span class="line">    <span class="type">float</span> x[<span class="number">4</span>]=&#123;<span class="number">0</span>&#125;; <span class="comment">//每种物品选取比例，初始化为0</span></span><br><span class="line">    <span class="built_in">Knapsack</span>(n,C,v,w,x);</span><br><span class="line">    cout&lt;&lt;<span class="string">&quot;物品选取比例情况为：&quot;</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">1</span>;i&lt;=n;i++)&#123;</span><br><span class="line">        cout&lt;&lt;x[i]&lt;&lt;<span class="string">&quot; &quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2><span id="回溯法">回溯法</span></h2></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">夙星夜寐</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://gitee.com/wawanaB_psgr/blog/2022/07/15/%E7%AE%80%E5%8D%95%E7%9A%84%E7%AE%97%E6%B3%95%E5%88%86%E6%9E%90/">https://gitee.com/wawanaB_psgr/blog/2022/07/15/简单的算法分析/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://gitee.com/wawanaB_psgr/blog" target="_blank">给点给点</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/%E7%AE%97%E6%B3%95/">算法</a></div><div class="post_share"><div class="social-share" data-image="/blog/img/default_cover.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/blog/img/avatar.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/blog/img/avatar.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2022/07/15/JavaWeb%EF%BC%881%EF%BC%89/"><img class="prev-cover" src= "" data-lazy-src="/blog/img/default_cover.png" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JavaWeb（1）之html基础</div></div></a></div><div class="next-post pull-right"><a href="/blog/2022/05/16/linux%E5%92%8Chadoop%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/"><img class="next-cover" src= "" data-lazy-src="/blog/img/default_cover.png" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">linux和hadoop简单使用</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/blog/img/avatar.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">夙星夜寐</div><div class="author-info__description"></div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">7</div></a></div><div class="card-info-data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">7</div></a></div><div class="card-info-data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div></div><a id="card-info-btn" href="https://gitee.com/wawanaB_psgr"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=3236373786&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">缓慢学习中，慢就是快，快就是好啊！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">穷举法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">1.1.</span> <span class="toc-text">百鸡问题</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.</span> <span class="toc-text">递归与分治</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">2.1.</span> <span class="toc-text">二分查找</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">2.2.</span> <span class="toc-text">归并排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">2.3.</span> <span class="toc-text">快速排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">2.4.</span> <span class="toc-text">循环赛日程表</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">3.</span> <span class="toc-text">动态规划</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">3.1.</span> <span class="toc-text">最长公共子序列</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">3.2.</span> <span class="toc-text">0-1背包问题</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">4.</span> <span class="toc-text">贪心算法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">4.1.</span> <span class="toc-text">活动安排问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">4.2.</span> <span class="toc-text">哈夫曼编码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">4.3.</span> <span class="toc-text">单源最短路径</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">4.4.</span> <span class="toc-text">最小生成树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">4.5.</span> <span class="toc-text">背包问题</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">5.</span> <span class="toc-text">回溯法</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/07/15/JavaWeb%EF%BC%881%EF%BC%89/" title="JavaWeb（1）之html基础"><img src= "" data-lazy-src="/blog/img/default_cover.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="JavaWeb（1）之html基础"/></a><div class="content"><a class="title" href="/blog/2022/07/15/JavaWeb%EF%BC%881%EF%BC%89/" title="JavaWeb（1）之html基础">JavaWeb（1）之html基础</a><time datetime="2022-07-15T08:28:20.000Z" title="发表于 2022-07-15 16:28:20">2022-07-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/07/15/%E7%AE%80%E5%8D%95%E7%9A%84%E7%AE%97%E6%B3%95%E5%88%86%E6%9E%90/" title="简单的算法分析"><img src= "" data-lazy-src="/blog/img/default_cover.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="简单的算法分析"/></a><div class="content"><a class="title" href="/blog/2022/07/15/%E7%AE%80%E5%8D%95%E7%9A%84%E7%AE%97%E6%B3%95%E5%88%86%E6%9E%90/" title="简单的算法分析">简单的算法分析</a><time datetime="2022-07-15T04:57:27.000Z" title="发表于 2022-07-15 12:57:27">2022-07-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/05/16/linux%E5%92%8Chadoop%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/" title="linux和hadoop简单使用"><img src= "" data-lazy-src="/blog/img/default_cover.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="linux和hadoop简单使用"/></a><div class="content"><a class="title" href="/blog/2022/05/16/linux%E5%92%8Chadoop%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/" title="linux和hadoop简单使用">linux和hadoop简单使用</a><time datetime="2022-05-16T12:28:33.000Z" title="发表于 2022-05-16 20:28:33">2022-05-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/05/15/%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/" title="架构设计"><img src= "" data-lazy-src="/blog/img/default_cover.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="架构设计"/></a><div class="content"><a class="title" href="/blog/2022/05/15/%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/" title="架构设计">架构设计</a><time datetime="2022-05-15T09:10:29.000Z" title="发表于 2022-05-15 17:10:29">2022-05-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/05/10/%E9%A5%BF%E4%BA%86/" title="饿了"><img src= "" data-lazy-src="/blog/img/default_cover.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="饿了"/></a><div class="content"><a class="title" href="/blog/2022/05/10/%E9%A5%BF%E4%BA%86/" title="饿了">饿了</a><time datetime="2022-05-10T14:10:50.000Z" title="发表于 2022-05-10 22:10:50">2022-05-10</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 By 夙星夜寐</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">前有黑暗剑，所以敬请见证</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body></html>